package com.junan.galiao.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


/**
 * @author junan
 * @version V1.0
 * @className GaLiaoServer
 * @disc 尬聊 netty 服务启动类
 * @date 2020/4/24 22:57
 */
@Component
public class GaLiaoServer {

    @Value("${netty.port}")
    private  int port;

    /**
     * 主线程组
     */
    private EventLoopGroup mainGroup;

    /**
     * 从线程组
     */
    private EventLoopGroup subGroup;

    /**
     * 启动server
     */
    private ServerBootstrap server;

    /**
     * 构造方法
     * @param gaLiaoServerInitializer
     */
    public GaLiaoServer(GaLiaoServerInitializer gaLiaoServerInitializer) {
        // 主线程组  接受请求
        mainGroup = new NioEventLoopGroup();
        // 从线程组  处理请求
        subGroup = new NioEventLoopGroup();
        server = new ServerBootstrap();
        server.group(mainGroup,subGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(gaLiaoServerInitializer);
    }

    /**
     * 启动 netty 服务
     */
    public void start(){
        try {
            ChannelFuture bind = server.bind(port).sync();
            bind.channel().closeFuture().sync();
        } catch (Exception e) {
            mainGroup.shutdownGracefully();
            subGroup.shutdownGracefully();
        }
    }
}